import {
  getUserProfile,
  updateUserPhoto,
  updateUserProfile,
} from '@/store/actions/user';
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile';
import classNames from 'classnames';
// import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';

// import { RootState } from '@/types/store';

import { EditInput } from './EditInput/EditInput';

import styles from './ProfileEdit.module.scss';
import { useInitialState } from '@/utils/use-initial-state';
import { useRef, useState } from 'react';
import { EditList } from './EditList/EditList';
import dayjs from 'dayjs';
import { logout } from '@/store/actions/login';

export const ProfileEdit = () => {
  // hooks
  const history = useHistory();
  const dispatch = useDispatch();

  // 页面数据
  // 页面UI状态
  // const [inputVisible, setInputVisible] = useState(false);
  const [popupState, setPopupState] = useState({
    prop: '',
    value: '',
    visible: false,
  });
  // 文件选择表单dom实例
  const fileRef = useRef<HTMLInputElement>(null);
  // 生日选择组件的显示状态
  const [birthday, setBirthday] = useState(false);

  // const profile = useSelector((state: RootState) => state.user.profile);
  // 使用自定义hooks
  const profile = useInitialState(getUserProfile, 'user').profile;

  // 父组件定义函数，接收子组件昵称改变后的值
  const onValueChange = async (value: string, prop: string) => {
    // console.log('值：', value, '属性：', prop);
    if (prop === 'photo') {
      // 处理头像（图片）
      // console.log('弹窗选择图片');
      // 模拟点击文件选择
      fileRef.current?.click();
    } else {
      // 发起更新用户信息action
      // 实际开发中，别忘了 try catch 异常处理
      await dispatch(updateUserProfile({ [prop]: value }));

      // 提示用户更新成功
      Toast.show({
        content: '更新成功',
        duration: 600,
      });
      // Toast.show({
      //   content: popupState.prop === 'name' ? '更新昵称成功' : '更新简介成功',
      //   duration: 600,
      // });

      // 关闭弹窗
      setPopupState({
        prop,
        value,
        visible: false,
      });
    }
  };

  // 选择生日事件处理函数
  const handleBirthday = async (date: Date) => {
    const birthday = dayjs(date).format('YYYY-MM-DD');
    // console.log(date);
    // console.log(birthday);
    // 提交给服务器更新
    await onValueChange(birthday, 'birthday');
    // 提示用户
    Toast.show({ content: '生日更新成功', duration: 600 });

    // 隐藏生日选择框
    setBirthday(false);
  };

  // 文件选择事件处理函数
  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(e);
    // 组装FromData对象
    if (!e.target.files) return;

    // 创建FormData实例
    const formData = new FormData();

    // 把图片文件放到 formData 中
    formData.append('photo', e.target.files[0]);

    // 把formData提交给后台服务器，发起请求。
    await dispatch(updateUserPhoto(formData));

    // 关闭弹窗
    setPopupState({
      prop: 'photo',
      value: 'cancel',
      visible: false,
    });
  };

  // 退出登录事件处理
  const handleLogout = () => {
    Dialog.show({
      title: '温馨提示',
      content: '亲，确定要退出登录码？',
      closeOnMaskClick: true,
      closeOnAction: true,
      actions: [
        [
          { key: 'cancel', text: '取消', style: { color: '#999' } },
          { key: 'confirm', text: '确定', onClick: handleToken },
        ],
      ],
    });
  };

  // 清空token
  const handleToken = () => {
    // console.log('清空token');
    dispatch(logout());

    history.replace('/login');
  };

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar onBack={() => history.goBack()}>个人信息</NavBar>
        <input
          type={'file'}
          hidden
          ref={fileRef}
          onChange={handlePhotoChange}
        />
        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <List.Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      profile.photo ??
                      'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow
              onClick={() =>
                setPopupState({
                  prop: 'photo',
                  value: profile.photo,
                  visible: true,
                })
              }
            >
              头像
            </List.Item>
            <List.Item
              arrow
              extra={profile.name}
              onClick={() =>
                setPopupState({
                  prop: 'name',
                  value: profile.name,
                  visible: true,
                })
              }
            >
              昵称
            </List.Item>
            <List.Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {profile.intro ?? '未填写'}
                </span>
              }
              onClick={() =>
                setPopupState({
                  prop: 'intro',
                  value: profile.intro ?? '',
                  visible: true,
                })
              }
            >
              简介
            </List.Item>
          </List>

          <List className="profile-list">
            <List.Item
              arrow
              extra={profile.gender + '' === '0' ? '男' : '女'}
              onClick={() =>
                setPopupState({
                  prop: 'gender',
                  value: profile.gender + '',
                  visible: true,
                })
              }
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthday(true)}
            >
              生日
            </List.Item>
          </List>

          <DatePicker
            visible={birthday}
            onCancel={() => setBirthday(false)}
            onConfirm={handleBirthday}
            value={new Date(profile.birthday)}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={handleLogout}>
            退出登录
          </Button>
        </div>
      </div>

      {/* 编辑昵称和简介 */}
      <Popup
        destroyOnClose
        visible={
          (popupState.prop === 'name' && popupState.visible) ||
          (popupState.prop === 'intro' && popupState.visible)
        }
        position={'right'}
      >
        <EditInput
          value={popupState.value}
          prop={popupState.prop}
          onClose={(value, prop) => {
            setPopupState({
              prop,
              value,
              visible: false,
            });
            // history.go(0); // 强制刷新页面也能实现效果，但是会卡顿
          }}
          onValueChange={onValueChange}
        />
      </Popup>

      {/* 编辑性别-头像 */}
      <Popup
        onMaskClick={() =>
          setPopupState({
            prop: popupState.prop,
            value: 'cancel',
            visible: false,
          })
        }
        visible={
          (popupState.prop === 'gender' && popupState.visible) ||
          (popupState.prop === 'photo' && popupState.visible)
        }
      >
        <EditList
          value={popupState.value}
          prop={popupState.prop}
          onClose={(value, prop) => {
            setPopupState({
              prop,
              value,
              visible: false,
            });
          }}
          onValueChange={onValueChange}
        />
      </Popup>
    </div>
  );
};
